package com.kykj.kykjyzw.config;

import com.kykj.kykjyzw.service.util.TokenToolService;
import jakarta.annotation.Resource;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

@WebFilter(urlPatterns="/*", filterName = "WebXFilter")
public class WebXFilter extends HttpFilter {

    @Resource
    TokenToolService tokenToolService;
    public void init(FilterConfig config) throws ServletException {
        System.out.println("程序启动！");
    }

    public void destroy() {
        System.out.println("程序销毁！");
    }

    @Override
    public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        ServletOutputStream outputStream = response.getOutputStream();//输出对象
        if (request.getMethod().equals("OPTIONS")){//如果是预检请求，统统允许通过(解决跨域问题)
            chain.doFilter(request, response);//允许通过
        }else {
            if (request.getRequestURI().equals("/v2/user/login")){ //允许通过的，就不校验token
                chain.doFilter(request, response);//允许通过
            }else {
                try {
                    String token =request.getHeader("token");//获取前段请求头的token
                    String uname = request.getHeader("uname");//获取前段请求头的uname
                    if (tokenToolService.isToKen(uname,token)){//请求头正确
                        chain.doFilter(request,response);//允许通过
                    }else {
                        outputStream.write("{\"code\":0,\"msg\":\"Token不存在！数据类型不符\"}".getBytes());
                        System.out.println("Token不存在！");
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    outputStream.write("{\"code\":-1,\"msg\":\"Token未传值！\"}".getBytes());
                    System.out.println("系统错误！");
                }
            }
        }


    }
}
